package com.xiaodeng.xdblogspringboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaodeng.xdblogspringboot.exception.UserException;
import com.xiaodeng.xdblogspringboot.mapper.UserMapper;
import com.xiaodeng.xdblogspringboot.pojo.Article;
import com.xiaodeng.xdblogspringboot.pojo.PageBean;
import com.xiaodeng.xdblogspringboot.pojo.User;
import com.xiaodeng.xdblogspringboot.service.UserService;
import com.xiaodeng.xdblogspringboot.utils.JwtUtil;
import com.xiaodeng.xdblogspringboot.utils.Md5Util;
import com.xiaodeng.xdblogspringboot.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    //用户名查询用户
    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }


    //用户注册
    @Override
    public void register(String username, String password, String email) {
        //用户名查询用户
        User u = this.findByUserName(username);
        if(u != null){
            throw new UserException(401,"该用户已存在");
        }
        //加密处理
        String md5String = Md5Util.getMD5String(password);
        //注册
        userMapper.add(username,md5String,email);
    }

    //用户登录
    @Override
    public String login(String username, String password) {
        //用户名查询用户
        User loginuser = this.findByUserName(username);
        if(loginuser == null){
            throw new UserException(401,"用户不存在");
        }
        if (!loginuser.getPassword().equals(Md5Util.getMD5String(password))){
            throw new UserException(402,"账号或者密码错误");
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",loginuser.getId());
        claims.put("username",loginuser.getUsername());
        claims.put("user_pic",loginuser.getUserPic());

        return JwtUtil.genToken(claims);
    }

    @Override
    public PageBean<Article> getArticle(Integer pageNum, Integer pageSize, Integer userId) {
        //创建pageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper
        List<Article> as = userMapper.getArticle(userId);
        Page<Article> p =(Page<Article>) as;
        //把数据填充到pageBean
        //获取总条数
        pb.setTotal(p.getTotal());
        //获取当前页的数据
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void sendEmail(String email, String verificationCode) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件的发件人
        message.setFrom("db020723@163.com");
        // 设置邮件的收件人
        message.setTo(email);
        message.setSubject("来自xdBlog:");
        message.setText("您的验证码是：" + verificationCode + ". 请在5分钟内使用。");
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件失败，请稍后再试。");
        }
    }


    //更新用户头像
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }

    //删除用户
    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    //更新用户信息
    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    //用户修改密码
    @Override
    public void updatePwd(String newPwd, User user) {

        //根据用户名拿到原密码跟新密码对比
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Integer id =(Integer) map.get("id");
        User loginUser = this.findByUserName(username);
        if (StrUtil.isBlank(user.getPassword()) ){
            throw new UserException(401,"原密码为空");
        }
        if (StrUtil.isBlank(loginUser.getPassword())){
            throw new UserException(401,"新密码为空");
        }
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(user.getPassword()))){
            throw new UserException(402,"请输入正确的原密码");
        }
        userMapper.updatePwd(Md5Util.getMD5String(newPwd), id);

    }
    @Override
    public int countNewUsersThisMonth(Date currentDate) {
        return userMapper.countNewUsersThisMonth(currentDate);
    }

}
